//
//  XWHAQAView.swift
//  XWHAOfflineFitting
//
//  Created by edy on 2024/11/20.
//

import UIKit

class XWHAQAView: XWHBaseView {
    
    lazy var titleLb = UILabel()
    lazy var replyBtn = UIButton()
    
    private(set) lazy var tableView = UITableView(frame: .zero, style: .plain)
    
    var qaList: [XWHAQAModel] = []

    var pullRefreshAction: ((_ isLoadMore: Bool) -> Void)?
    var clickReplyBtnAction: (() -> Void)?
    var clickImageAction: ((_ atIndex: Int, _ imageUrls: [String]) -> Void)?

    
    override func addSubViews() {
        super.addSubViews()
        
        addSubview(titleLb)
        addSubview(replyBtn)
        addSubview(tableView)

        config(titleLb: titleLb)
        config(btn: replyBtn)
        
        config(tableView: tableView)
        
        registerViews()
        
        titleLb.text = "专业建议指导"
        replyBtn.setTitle("回复", for: .normal)
    }
    
    private func config(titleLb: UILabel) {
        let font = AppFont.harmonyOSSans(ofSize: 24, weight: .medium)
        titleLb.textAlignment = .left
        titleLb.font = font
        titleLb.textColor = majorTextColor
        titleLb.adjustsFontSizeToFitWidth = true
    }
    
    func config(btn: UIButton) {
        let font = AppFont.harmonyOSSans(ofSize: 18, weight: .regular)
        btn.titleLabel?.font = font
        btn.setTitleColor(UIColor.white, for: .normal)

        btn.layer.cornerRadius = 8
        btn.layer.backgroundColor = btnBgColor.cgColor
        
        btn.addTarget(self, action: #selector(clickBtn(sender:)), for: .touchUpInside)
    }
    
    private func config(tableView: UITableView) {
        tableView.dataSource = self
        tableView.delegate = self
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.automaticallyAdjustsScrollIndicatorInsets = false
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.separatorInset = UIEdgeInsets(horizontal: 8, vertical: 0)
        tableView.separatorColor = collectionBgColor
        tableView.contentInset = .zero
                
        tableView.tableHeaderView = UIView()
        tableView.tableFooterView = UIView()
    }
    
    @objc func clickBtn(sender: UIButton) {
        clickReplyBtnAction?()
    }
    
    func addRefreshHeader() {
        tableView.addHeader { [weak self] in
            guard let self = self else {
                return
            }
            
            self.pullRefreshAction?(false)
        }
    }
    
    func addRefreshFooter() {
        if tableView.mj_footer != nil {
            return
        }
//        tableView.addFooter { [weak self] in
//            guard let self = self else {
//                return
//            }
//            
//            self.pullRefreshAction?(true)
//        }
        
        tableView.addAutoFooter { [weak self] in
            guard let self = self else {
                return
            }

            self.pullRefreshAction?(true)
        }
    }
    
    override func relayoutSubViews() {
        titleLb.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(24)
            make.top.equalToSuperview().inset(20)
            make.height.equalTo(34)
            make.width.lessThanOrEqualTo(124)
        }
        replyBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(24)
            make.width.equalTo(74)
            make.bottom.equalToSuperview().inset(24)
            make.height.equalTo(36)
        }
    }
    
    func registerViews() {
        tableView.register(cellWithClass: XWHAQAReplyTBCell.self)
        
        tableView.register(cellWithClass: XWHAQAQuestionTBCell.self)
    }
    
}

// MARK: - UITableViewDataSource & UITableViewDelegate & UITableViewRoundedProtocol
@objc extension XWHAQAView: UITableViewDataSource & UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return qaList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
//        let section = indexPath.section
        let row = indexPath.row
        let viewWidth = width
        let tbViewWidth = tableView.width
        if viewWidth == 0 || tbViewWidth == 0 {
            return 0
        }
        
        let qaModel = qaList[row]
        
        /// 0表示用户的提问，1表示验配师回复
//        let qaType = qaModel.chatType
        
        let tcMargin = XWHAQAReplyTBCell.textContentMargin
        let textContentWidth = tbViewWidth - 2 * tcMargin
        var imageViewHeight: CGFloat = 0
        let text = qaModel.content
        if !qaModel.extraImg.isEmpty {
            imageViewHeight = 64
        }
        
        let textHeight = text.heightWith(width: textContentWidth, lineSpacing: nil, font: XWHAQAReplyTBCell.textFont)
        let titleHeight: CGFloat = XWHAQAReplyTBCell.titleHeight
        let padding: CGFloat = XWHAQAReplyTBCell.padding
        let retHeight = XWHAQAReplyTBCell.margin + titleHeight + padding + textHeight + padding * 2 + imageViewHeight
        
        return retHeight
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        let section = indexPath.section
        let row = indexPath.row
        let qaModel = qaList[row]
        /// 0表示用户的提问，1表示验配师回复
        let qaType = qaModel.chatType
        
        if qaType == 0 {
            let cell = tableView.dequeueReusableCell(withClass: XWHAQAQuestionTBCell.self, for: indexPath)
            cell.clickImageCallback = { [weak self] sIndex in
                guard let self = self else {
                    return
                }
                
                self.clickImageAction?(sIndex, qaModel.extraImg)
            }
            
            cell.update(info: qaModel)
            
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: XWHAQAReplyTBCell.self, for: indexPath)
            cell.update(info: qaModel)
            
            return cell
        }
    }
    
//   override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//       rounded(tableView, willDisplay: cell, forRowAt: indexPath)
//    }
    
//    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 0.001
//    }
//
//    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        return UIView()
//    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let cView = UIView()
        cView.backgroundColor = .clear
        
        return cView
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let row = indexPath.row
//        let qaModel = qaList[row]
        
    }
    
}
